<template>
  <div class="container mx-auto px-4 py-8">
    <!-- 标题和工具栏 -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-900">组织管理</h1>
      <div class="flex space-x-4">
        <select v-model="currentView" 
                class="rounded border-gray-300 shadow-sm">
          <option value="tree">树形视图</option>
          <option value="chart">组织架构图</option>
        </select>
        <button @click="showAddModal = true" 
                class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
          添加组织
        </button>
      </div>
    </div>

    <!-- 过滤器 -->
    <div class="bg-white p-4 rounded-lg shadow mb-6">
      <div class="flex space-x-4">
        <select v-model="filterType" 
                class="rounded border-gray-300 shadow-sm">
          <option value="">全部类型</option>
          <option value="PARTY">党组织</option>
          <option value="ECONOMIC">经济组织</option>
          <option value="SOCIAL">社会组织</option>
        </select>
        
        <select v-model="filterRegion" 
                class="rounded border-gray-300 shadow-sm">
          <option value="">全部区划</option>
          <option v-for="region in regions" 
                  :key="region.code" 
                  :value="region.code">
            {{ region.name }}
          </option>
        </select>
      </div>
    </div>

    <!-- 树形视图 -->
    <div v-if="currentView === 'tree'" 
         class="bg-white rounded-lg shadow overflow-hidden">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
          <tr>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">所属区划</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">负责人</th>
            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
          </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
          <template v-for="org in displayOrganizations" :key="org.id">
            <tr class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                <div class="flex items-center">
                  <span :style="{ marginLeft: `${(org.level - 1) * 20}px` }" class="flex items-center">
                    <button v-if="hasChildren(org.id)"
                            @click="toggleNode(org)"
                            class="mr-2 w-4 text-gray-500 focus:outline-none">
                      <span v-if="loadingStates[org.id]">
                        <svg class="animate-spin h-4 w-4" viewBox="0 0 24 24">
                          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle>
                          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                      </span>
                      <span v-else>
                        {{ expandedNodes.has(org.id) ? '▼' : '▶' }}
                      </span>
                    </button>
                    <span v-else class="w-4 mr-2"></span>
                    {{ org.name }}
                  </span>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                {{ getOrgTypeText(org.type) }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                {{ org.region?.name }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                {{ org.leader }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                <button @click="editOrg(org)" 
                        class="text-blue-600 hover:text-blue-900 mr-3">
                  编辑
                </button>
                <button @click="deleteOrg(org)" 
                        class="text-red-600 hover:text-red-900">
                  删除
                </button>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>

    <!-- 组织架构图 -->
    <div v-else class="bg-white rounded-lg shadow p-4">
      <div class="h-[600px]">
        <OrgChart :data="chartData" />
      </div>
    </div>

    <!-- 添加/编辑模态框 -->
    <div v-if="showAddModal || showEditModal" 
         class="fixed inset-0 bg-gray-600 bg-opacity-50 flex items-center justify-center">
      <div class="bg-white rounded-lg p-8 max-w-md w-full">
        <h2 class="text-xl font-bold text-gray-900 mb-4">
          {{ showEditModal ? '编辑组织' : '添加组织' }}
        </h2>
        
        <form @submit.prevent="handleSubmit" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700">名称</label>
            <input v-model="formData.name" 
                   type="text" 
                   required
                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700">类型</label>
            <select v-model="formData.type" 
                    required
                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
              <option value="PARTY">党组织</option>
              <option value="ECONOMIC">经济组织</option>
              <option value="SOCIAL">社会组织</option>
            </select>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700">所属区划</label>
            <select v-model="formData.regionCode" 
                    required
                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
              <option v-for="region in regions" 
                      :key="region.code" 
                      :value="region.code">
                {{ region.name }}
              </option>
            </select>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700">上级组织</label>
            <select v-model="formData.parentId" 
                    class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
              <option :value="null">无</option>
              <option v-for="org in parentOptions" 
                      :key="org.id" 
                      :value="org.id">
                {{ org.name }}
              </option>
            </select>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700">负责人</label>
            <input v-model="formData.leader" 
                   type="text"
                   class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700">描述</label>
            <textarea v-model="formData.description" 
                      class="mt-1 block w-full rounded-md border-gray-300 shadow-sm"
                      rows="3"></textarea>
          </div>

          <div class="flex justify-end space-x-3 mt-6">
            <button type="button" 
                    @click="closeModal"
                    class="px-4 py-2 text-gray-700 bg-gray-100 rounded hover:bg-gray-200">
              取消
            </button>
            <button type="submit"
                    class="px-4 py-2 text-white bg-blue-500 rounded hover:bg-blue-600">
              确定
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
const currentView = ref('tree')
const filterType = ref('')
const filterRegion = ref('')
const organizations = ref(new Map())
const expandedNodes = ref(new Set())
const loadingStates = ref({})
const displayOrganizations = ref([])
const regions = ref([])
const showAddModal = ref(false)
const showEditModal = ref(false)
const formData = ref({
  name: '',
  code: '',
  type: 'PARTY',
  regionCode: '',
  parentId: null,
  level: 1,
  description: '',
  leader: ''
})

// 组织类型文本映射
const orgTypeText = {
  PARTY: '党组织',
  ECONOMIC: '经济组织',
  SOCIAL: '社会组织'
}

// 获取组织类型显示文本
const getOrgTypeText = (type) => orgTypeText[type] || type

// 获取区划列表
const fetchRegions = async () => {
  try {
    const response = await $fetch('/api/regions')
    regions.value = response.regions
  } catch (error) {
    console.error('获取区划列表失败:', error)
  }
}

// 获取顶级组织
const fetchTopLevelOrgs = async () => {
  try {
    const response = await $fetch('/api/organizations', {
      params: {
        level: 1,
        type: filterType.value,
        regionCode: filterRegion.value
      }
    })
    displayOrganizations.value = response.organizations
    response.organizations.forEach(org => {
      organizations.value.set(org.id, org)
    })
  } catch (error) {
    console.error('获取组织列表失败:', error)
  }
}

// 加载子组织
const fetchChildren = async (parentId) => {
  try {
    loadingStates.value[parentId] = true
    const response = await $fetch('/api/organizations', {
      params: {
        parentId,
        type: filterType.value,
        regionCode: filterRegion.value
      }
    })
    
    response.organizations.forEach(org => {
      organizations.value.set(org.id, org)
    })
    
    updateDisplayOrganizations()
  } catch (error) {
    console.error('获取子组织失败:', error)
  } finally {
    loadingStates.value[parentId] = false
  }
}

// 切换节点展开状态
const toggleNode = async (org) => {
  if (expandedNodes.value.has(org.id)) {
    expandedNodes.value.delete(org.id)
  } else {
    expandedNodes.value.add(org.id)
    if (!hasLoadedChildren(org.id)) {
      await fetchChildren(org.id)
    }
  }
  
  updateDisplayOrganizations()
}

// 检查是否已加载子节点
const hasLoadedChildren = (parentId) => {
  return Array.from(organizations.value.values()).some(org => org.parentId === parentId)
}

// 更新显示列表
const updateDisplayOrganizations = () => {
  const result = []
  
  // 添加顶级组织
  const topLevel = Array.from(organizations.value.values())
    .filter(org => org.level === 1)
    .sort((a, b) => a.code.localeCompare(b.code))
  
  for (const org of topLevel) {
    result.push(org)
    if (expandedNodes.value.has(org.id)) {
      addExpandedChildren(org.id, result)
    }
  }
  
  displayOrganizations.value = result
}

// 递归添加已展开的子组织
const addExpandedChildren = (parentId, result) => {
  const children = Array.from(organizations.value.values())
    .filter(org => org.parentId === parentId)
    .sort((a, b) => a.code.localeCompare(b.code))
  
  for (const child of children) {
    result.push(child)
    if (expandedNodes.value.has(child.id)) {
      addExpandedChildren(child.id, result)
    }
  }
}

// 编辑组织
const editOrg = (org) => {
  formData.value = { ...org }
  showEditModal.value = true
}

// 删除组织
const deleteOrg = async (org) => {
  if (!confirm(`确定要删除"${org.name}"吗？删除后其下级组织也会被删除！`)) {
    return
  }
  
  try {
    await $fetch(`/api/organizations/${org.id}`, {
      method: 'DELETE'
    })
    
    // 从本地数据中移除
    const removeOrgAndChildren = (id) => {
      const children = Array.from(organizations.value.values())
        .filter(o => o.parentId === id)
      
      children.forEach(child => {
        removeOrgAndChildren(child.id)
      })
      
      organizations.value.delete(id)
      expandedNodes.value.delete(id)
    }
    
    removeOrgAndChildren(org.id)
    updateDisplayOrganizations()
    alert('删除成功')
  } catch (error) {
    console.error('删除组织失败:', error)
    alert(error.data?.message || '删除失败')
  }
}

// 生成组织架构图数据
const chartData = computed(() => {
  const data = {
    name: '组织架构',
    children: []
  }
  
  // 根据筛选条件获取顶级节点
  const topLevel = Array.from(organizations.value.values())
    .filter(org => {
      const typeMatch = !filterType.value || org.type === filterType.value
      const regionMatch = !filterRegion.value || org.regionCode === filterRegion.value
      return org.level === 1 && typeMatch && regionMatch
    })
  
  // 递归构建树形数据
  const buildTreeData = (orgs) => {
    return orgs.map(org => {
      const children = Array.from(organizations.value.values())
        .filter(o => o.parentId === org.id)
      
      return {
        name: org.name,
        value: org.id,
        children: children.length ? buildTreeData(children) : undefined
      }
    })
  }
  
  data.children = buildTreeData(topLevel)
  return data
})

// 监听筛选条件变化
watch([filterType, filterRegion], () => {
  organizations.value.clear()
  expandedNodes.value.clear()
  fetchTopLevelOrgs()
})

// 初始化
onMounted(() => {
  fetchRegions()
  fetchTopLevelOrgs()
})
</script> 